﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Drawing;
using OCR.Algorithm;
using OCR.Function;
using OCR.Config;
using System.Reflection;
using System.Drawing.Imaging;

namespace OCR.SettingsForm
{
    public partial class TestScaleForm : Form
    {
        private int scaleFactor = 4;
        public TestScaleForm()
        {
            InitializeComponent();
        }
        public static Thread TestScale_Thread = null;
        public static bool TestScale_Flowrec = false;

        public static bool TestScale_FlowrecPause = false;

        public static DateTime triggerDataTime;

        public static string currInfo;

        public static List<List<string>> infosList = new List<List<string>>();
        public static List<List<bool>> insideList = new List<List<bool>>();
        public static List<List<List<Point>>> finalPointlists = new List<List<List<Point>>>();

        public static List<string> currInfos = new List<string>();

        Font font = new Font("微软雅黑", 20, FontStyle.Regular);
        Brush brush = new SolidBrush(Color.Red);

        public static Bitmap saveBitmap;

        //鼠标是否在拖拽中
        private bool IsMove = false;
        //鼠标点击的位置
        private Point MouseDownPoint;

        public Bitmap originBitmap;
        private void TestScaleForm_Load(object sender, EventArgs e)
        {
            Console.OutputEncoding = Encoding.UTF8;

            AlgorithmModule_GPU.CreateInstance();

            //AddTextToImage((Bitmap)img, "22");

            TestScale_Thread = new Thread(TestFlow_Thread);
            TestScale_Thread.IsBackground = true;
            TestScale_Thread.Start();
            TestScale_Flowrec = true;
            TestScale_FlowrecPause = true;
            checkBox1.Checked = TestScale_FlowrecPause;

            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

            pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox2.BackgroundImageLayout = ImageLayout.Zoom;



            LocalInfo.Tem_RectMaxCount = 5;

            for (int i = 0; i < LocalInfo.Tem_RectMaxCount; i++)
            {
                infosList.Add(new List<string>());
                insideList.Add(new List<bool>());
                finalPointlists.Add(new List<List<Point>>());
                currInfos.Add(string.Empty);
            }

            LocalTemplateSingleInfos_Config.LocalTemplateSingleInfosInitial();

            saveBitmap = (Bitmap)Image.FromFile("TemplateInput\\2025-05-14-11-00-30-381.bmp");

            AlgorithmModule_GPU.ImageHandleV2_ByteArray(saveBitmap);

            pictureBox1.Image = AlgorithmModule_GPU.RectPoints1((Bitmap)Image.FromFile("TemplateInput\\2025-05-14-11-00-30-381.bmp"), AlgorithmModule_GPU.pointsList, AlgorithmModule_GPU.currConfigs);

            pointsList = AlgorithmModule_GPU.pointsList;

            PicStartPos = pictureBox1.Location;
            PicSize = pictureBox1.Size;
            pictureBox1.MouseWheel += new MouseEventHandler(pictureBox1_MouseWheel);

            originBitmap = (Bitmap)AlgorithmModule_GPU.RectPoints1((Bitmap)Image.FromFile("TemplateInput\\2025-05-14-11-00-30-381.bmp"), AlgorithmModule_GPU.pointsList, AlgorithmModule_GPU.currConfigs);
        }
        private void TestFlow_Thread(object obj)
        {
            while (TestScale_Flowrec)
            {
                if (!TestScale_FlowrecPause)
                {
                    Console.WriteLine("开始");
                    //AlgorithmModule_CPU.ImageHandleV2_Refresh(Application.StartupPath + "\\TemplateInput\\Refresh.bmp");

                    //Image bitmap = AlgorithmModule_CPU.ImageHandleV2_Scale4_Local("TemplateInput\\First.bmp", "First1.bmp", scaleFactor);
                    //pictureBox1.Image = AlgorithmModule_CPU.RectPoints(bitmap);

                    //AlgorithmModule_CPU.ImageHandleV2_Scale4_Local("RectOutput.bmp", "First12.bmp", 2);
                    //pictureBox1.Image = AlgorithmModule_CPU.RectPoints(new Bitmap("TemplateInput\\First.bmp"), AlgorithmModule_CPU.convertList);

                    //pictureBox1.Image = AlgorithmModule_CPU_V2.CropImage(new Bitmap("TemplateInput\\First.bmp"), currRect);
                }

            }
        }

        private void TestScaleForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            TestScale_Flowrec = false;
            TestScale_Thread.Join();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AlgorithmModule_GPU.ImageHandleV2_ByteArray(Application.StartupPath + "\\TemplateInput\\2025-05-14-11-00-30-381.bmp");

            pictureBox1.Image = AlgorithmModule_GPU.RectPoints1((Bitmap)Image.FromFile("TemplateInput\\2025-05-14-11-00-30-381.bmp"),  AlgorithmModule_GPU.pointsList, AlgorithmModule_GPU.currConfigs);

            pointsList = AlgorithmModule_GPU.pointsList;

            //Test();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //TestScale_Flowrec = !TestScale_Flowrec;
            //if (TestScale_Flowrec)
            //{
            //    //TestScale_Thread = new Thread(TestFlow_Thread);
            //    TestScale_Thread.Start();
            //}
            //else
            //{
            //    TestScale_Thread.Join();
            //}
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            scaleFactor =int.Parse( textBox1.Text);
            Console.WriteLine("缩放倍数： " +scaleFactor);
        }

        private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
        {
            TestScale_FlowrecPause = checkBox1.Checked;
            Console.WriteLine("TestScale_FlowrecPause: "+TestScale_FlowrecPause);
        }
        private bool isDrawing = false;
        private Point startPoint = Point.Empty;
        Rectangle rect = new Rectangle();
        Rectangle currRect = new Rectangle();

        private List<Rectangle> rectangles = new List<Rectangle>();

        private readonly double ratio = 1624.0 / 1240.0; // 固定比例16:9
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            Console.WriteLine("down_rectangles.Count: " + rectangles.Count);

            if (e.Button == MouseButtons.Left)
            {
                if (rectangles.Count >= LocalInfo.Tem_RectMaxCount)
                {
                    //return;
                    MessageBox.Show("已到画框上限");
                }

                isDrawing = true;
                startPoint = e.Location;
                pictureBox1.Invalidate();

            }
            if (e.Button == MouseButtons.Right)
            {
                //rectangles.Clear();
                //rect = Rectangle.Empty;
                //pictureBox1.Invalidate();

                //设置坐标
                pictureBox1.Location = PicStartPos;
                //设置控件宽高
                pictureBox1.Size = PicSize;
            }

            if (pictureBox1.Image == null) return;

            if (e.Button == MouseButtons.Middle)
            {
                MouseDownPoint.X = Cursor.Position.X; //记录鼠标左键按下时位置
                MouseDownPoint.Y = Cursor.Position.Y;
                IsMove = true;
                pictureBox1.Focus(); //鼠标滚轮事件(缩放时)需要picturebox有焦点
            }
        }
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (isDrawing)
                {
                    //Console.WriteLine("pictureBox1_MouseMove");
                    // Point current = e.Location;
                    // int dx = current.X - startPoint.X;
                    // int dy = current.Y - startPoint.Y;
                    // 根据比例调整宽高
                    // int width, height;
                    // if (Math.Abs(dx) > Math.Abs(dy * ratio))
                    // {
                    //     width = dx;
                    //     height = (int)(width / ratio);
                    // }
                    // else
                    // {
                    //     height = dy;
                    //     width = (int)(height * ratio);
                    // }
                    // 处理反向拖动
                    // int x = startPoint.X;
                    // int y = startPoint.Y;
                    // if (dx < 0) x = current.X;
                    // if (dy < 0) y = current.Y;
                    // 确保宽高为正
                    //width = Math.Abs(width);
                    // height = Math.Abs(height);


                    int x = e.X > startPoint.X ? startPoint.X : e.X;
                    int y = e.Y > startPoint.Y ? startPoint.Y : e.Y;
                    int width = Math.Abs(e.X - startPoint.X);
                    int height = Math.Abs(e.Y - startPoint.Y);


                    rect = new Rectangle(x, y, width, height);

                    //if (pictureBox1.Width == 812)
                    //{

                    //}
                    //else if (pictureBox1.Width == 1624)
                    //{
                    //    rect = new Rectangle(rect.X / 2, rect.Y / 2, rect.Width / 2, rect.Height / 2);
                    //}
                    //else if (pictureBox1.Width == 406)
                    //{
                    //    rect = new Rectangle(rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2);
                    //}

                    currRect = new Rectangle(x*2, y*2, width*2, height*2);
                    pictureBox1.Invalidate();

                    //font = new Font("微软雅黑", 20, FontStyle.Regular);
                    //brush = new SolidBrush(Color.Red);
                }
            }

            if (pictureBox1.Image == null) return;
            pictureBox1.Focus(); //鼠标在picturebox上时才有焦点，此时可以缩放
            if (IsMove)
            {
                int x, y;   //新的pictureBox1.Location(x,y)
                int moveX, moveY; //X方向，Y方向移动大小。
                moveX = Cursor.Position.X - MouseDownPoint.X;
                moveY = Cursor.Position.Y - MouseDownPoint.Y;
                x = pictureBox1.Location.X + moveX;
                y = pictureBox1.Location.Y + moveY;
                pictureBox1.Location = new Point(x, y);
                MouseDownPoint.X = Cursor.Position.X;
                MouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (rectangles.Count >= LocalInfo.Tem_RectMaxCount)
            {
                return;
                //MessageBox.Show("已到画框上限");
            }
            if (e.Button == MouseButtons.Left)
            {
                //Console.WriteLine("pictureBox1_MouseUp");
                isDrawing = false;
              



                brush = new SolidBrush(Color.Empty);

                Console.WriteLine("up_rectangles.Count: " + rectangles.Count);

                if (pictureBox1.Width == 812)
                {

                }
                else if (pictureBox1.Width == 1624)
                {
                    rect = new Rectangle(rect.X / 2, rect.Y / 2, rect.Width / 2, rect.Height / 2);
                }
                else if (pictureBox1.Width == 406)
                {
                    rect = new Rectangle(rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2);
                }

                Console.WriteLine("rect.X: " + rect.X + " rect.Y: " + rect.Y + " rect.Width: " + rect.Width + " rect.Height: " + rect.Height);
                Console.WriteLine("rect.Location: " + rect.Location + " rect.Right: " + rect.Right + " rect.Left: " + rect.Left + " rect.Top: " + rect.Top + " rect.Bottom: " + rect.Bottom);
                Console.WriteLine("rect.X: " + rect.X * 2 + " rect.Y: " + rect.Y * 2 + " rect.Width: " + rect.Width * 2 + " rect.Height: " + rect.Height * 2);


                pictureBox1.Image = RectPoints((Bitmap)pictureBox1.Image, new Rectangle(rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2));

                rectangles.Add(rect);

                Test2();
                //using(Graphics graphics = Graphics.FromImage(pictureBox1.Image))
                //{
                //    graphics.DrawString((rectangles.Count + 1).ToString(), font, brush, new PointF(rect.X, rect.Y));
                //}
                //rectangles.Clear();
                rect = Rectangle.Empty;
                pictureBox1.Invalidate();
            }


            if (e.Button == MouseButtons.Middle)
            {
                IsMove = false;
            }
        }



        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {

            //Console.WriteLine("pictureBox1_Paint");
            // 绘制所有已完成的矩形
            //foreach (var rect in rectangles)
            //{
            //    e.Graphics.DrawRectangle(new Pen(Color.Red, 4), rect);
            //}
            for (int i = 0; i < rectangles.Count; i++)
            {
                //e.Graphics.DrawRectangle(new Pen(Color.Red, 4), rectangles[i]);
                //e.Graphics.DrawString((i+1).ToString(), font, brush, new PointF(rectangles[i].X, rectangles[i].Y));
            }

            e.Graphics.DrawRectangle(new Pen(Color.Red, 4), rect);
            //e.Graphics.DrawString((rectangles.Count+1).ToString(), font, brush, new PointF(rect.X, rect.Y));




        }

        public void AddTextToImage(string imagePath, string savePath, string text)
        {
            // 加载原始图片
            using (Bitmap bitmap = new Bitmap(imagePath))
            {
                // 创建Graphics对象
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    // 设置文字样式
                    Font font = new Font("Arial", 20, FontStyle.Bold);
                    Brush brush = new SolidBrush(Color.Red);

                    // 计算文字位置（右下角）
                    PointF position = new PointF(
                        bitmap.Width - 200,
                        bitmap.Height - 50);

                    // 绘制文字
                    graphics.DrawString(text, font, brush, position);
                }

                // 保存图片
                bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }

        public Image AddTextToImage(Bitmap bitmap, string text)
        {
            // 创建Graphics对象
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                // 设置文字样式
                Font font = new Font("微软雅黑", 20, FontStyle.Regular);
                Brush brush = new SolidBrush(Color.Red);

                // 计算文字位置（右下角）
                PointF position = new PointF(
                    bitmap.Width - 200,
                    bitmap.Height - 50);

                // 绘制文字
                graphics.DrawString(text, font, brush, position);
            }
            pictureBox1.Image = bitmap;
            return bitmap;

        }

        //"这是一个非常长的文本示例，演示自动换行功能如何工作。文字超过指定宽度时会自动换到下一行。",
        public Bitmap AddMultiLineText(Bitmap sourceImage, string text, RectangleF textArea)
        {
            using (Graphics g = Graphics.FromImage(sourceImage))
            {
                // 启用高质量呈现模式
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                // 创建文本格式
                StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox)
                {
                    Alignment = StringAlignment.Near,     // 左对齐
                    LineAlignment = StringAlignment.Near, // 顶部对齐
                    Trimming = StringTrimming.Word        // 按单词截断
                };
                Font font = new Font("微软雅黑", 24, FontStyle.Bold, GraphicsUnit.Pixel);
                Color color = Color.White;
                // 创建文本画笔
                using (SolidBrush brush = new SolidBrush(color))
                {
                    // 自动换行关键设置：指定绘制矩形区域
                    g.DrawString(text, font, brush, textArea, format);
                }
            }
            return sourceImage;
        }

        public Bitmap AddMultiLineText(Bitmap sourceImage
            ,List<string> currinfos,List<RectangleF> rectangleAreas)
        {
            using (Graphics g = Graphics.FromImage(sourceImage))
            {
                // 启用高质量呈现模式
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                // 创建文本格式
                StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox)
                {
                    Alignment = StringAlignment.Near,     // 左对齐
                    LineAlignment = StringAlignment.Near, // 顶部对齐
                    Trimming = StringTrimming.Word        // 按单词截断
                };
                Font font = new Font("微软雅黑", 24, FontStyle.Bold, GraphicsUnit.Pixel);
                Color color = Color.White;

                // 创建文本画笔
                SolidBrush brush = new SolidBrush(color);
                //using (SolidBrush brush = new SolidBrush(color))
                //{

                //}
                // 自动换行关键设置：指定绘制矩形区域
                for (int i = 0; i < rectangles.Count; i++)
                {
                    g.DrawString(currinfos[i], font, brush, rectangleAreas[i], format);
                }
            }
            return sourceImage;
        }

        List<string> infos = new List<string>();
        List<bool> inside = new List<bool>();
        public static List<List<Point>> pointsList = new List<List<Point>>();

        public static List<List<Point>> finalPointsList = new List<List<Point>>();
        public static List<string> mainInfos = new List<string>();
        public void Compare(Rectangle rect,List<string> infos, List<bool> inside,List<List<Point>> finalPointList)
        {
            infos.Clear();
            inside.Clear();
            bool isInsideRect = true;
            Console.WriteLine("识别框个数：" + pointsList.Count);
            Console.WriteLine("rect.X: " + rect.X.ToString() + "  y: " + rect.Y.ToString());
            Console.WriteLine("rect.X: " + (rect.X * 2).ToString() + "  y: " + (rect.Y * 2).ToString());
            foreach (var item in pointsList)
            {
                foreach (var x in item)
                {

                    bool x_Inside = rect.X * 2 <= x.X & x.X <= rect.Right * 2;
                    bool y_Inside = rect.Y * 2 <= x.Y & x.Y <= rect.Bottom * 2;
                    Console.WriteLine("x: " + x_Inside.ToString() + "  y: " + y_Inside.ToString() + "  x&y: " + (x_Inside & y_Inside).ToString());
                    if (!(x_Inside & y_Inside))
                    {
                        isInsideRect = false;
                        break;
                    }
                    else
                    {
                        isInsideRect = true;
                    }
                }
                inside.Add(isInsideRect);
            }


            for (int i = 0; i < inside.Count; i++)
            {
                if (inside[i])
                {
                    infos.Add(AlgorithmModule_GPU.currConfigs[i].text);
                }
                else
                {
                    //infos.Add(string.Empty);
                }

            }
            Console.WriteLine("框选信息个数：" + infos.Count);
            for (int i = 0; i < infos.Count; i++)
            {
                Console.WriteLine("框选信息内容" + i + "：" + infos[i]);
            }

            for (int i = 0; i < inside.Count; i++)
            {
                Console.WriteLine("当前画框内" + i + "：" + inside[i]);
            }

            for (int i = 0; i < pointsList.Count; i++)
            {
                Console.WriteLine("inside_点数组: " + inside[i]);
                if (inside[i])
                {
                    finalPointsList.Add(pointsList[i]);
                    mainInfos.Add(AlgorithmModule_GPU.currConfigs[i].text);
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            rectangles.Clear();
            rect = Rectangle.Empty;
            pictureBox1.Invalidate();


            AlgorithmModule_GPU.ImageHandleV2_ByteArray(Application.StartupPath + "\\TemplateInput\\2025-05-14-11-00-30-381.bmp");

            //pictureBox1.Image = AlgorithmModule_GPU.RectPoints((Bitmap)Image.FromFile("TemplateInput\\2025-05-14-11-00-30-381.bmp"), AlgorithmModule_GPU.pointsList);
            pictureBox1.Image = AlgorithmModule_GPU.RectPoints1((Bitmap)Image.FromFile("TemplateInput\\2025-05-14-11-00-30-381.bmp"), AlgorithmModule_GPU.pointsList, AlgorithmModule_GPU.currConfigs);

            pointsList = AlgorithmModule_GPU.pointsList;
        }

        public void Test()
        {
            Bitmap img = (Bitmap)pictureBox1.Image;
            using (Graphics g = Graphics.FromImage(img))
            {
                //g.Clear(Color.White);

                // 创建文本绘制器
                var drawer = new MultiTextDrawer();

                // 准备要绘制的文本项
                var textItems = new List<TextPosition>{
            // 左上角标题（使用百分比坐标）
            new TextPosition("产品证书", 5, 5,
                new Font("微软雅黑", 24, FontStyle.Bold, GraphicsUnit.Pixel),
                Color.White),
                
            // 右下角日期（绝对坐标）
            new TextPosition(DateTime.Now.ToString("yyyy-MM-dd"),
                new PointF(600, 550),
                new Font("Arial", 12),
                Color.Gray),
                
            // 带背景的警告文本
            new TextPosition("警告：禁止复制", 50, 90,
                new Font("黑体", 16, FontStyle.Underline),
                Color.Red) { BackColor = Color.LightYellow }
        };

                // 执行绘制
                Bitmap result = drawer.DrawTexts(img, textItems);

                pictureBox1.Image = result;
                result.Save("output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }

        public void Test1(List<string> currInfos,List<RectangleF> rectangleFs)
        {
            Bitmap img = (Bitmap)pictureBox1.Image;
            //Console.WriteLine("currInfos[0]:"+ currInfos[0]);
            using (Graphics g = Graphics.FromImage(img))
            {
                //g.Clear(Color.White);

                // 创建文本绘制器
                var drawer = new MultiTextDrawer();

                // 准备要绘制的文本项
                var textItems = new List<TextPosition>{


            // 左上角标题（使用百分比坐标）
            new TextPosition(currInfos[0], new PointF(20, 20),
                new Font("微软雅黑", 24, FontStyle.Bold,GraphicsUnit.Pixel),
                Color.White),
                
            // 右下角日期（绝对坐标）
            new TextPosition(currInfos[1],
                new PointF(250, 20),
                new Font("微软雅黑", 24, FontStyle.Bold,GraphicsUnit.Pixel),
                Color.White),
                
            //// 带背景的警告文本
            //new TextPosition("警告：禁止复制", 50, 90,
            //    new Font("黑体", 16, FontStyle.Underline),
            //    Color.Red) { BackColor = Color.LightYellow }
        };

                // 执行绘制
                Bitmap result = drawer.DrawTexts(img, textItems);
                pictureBox1.Image = result;
                result.Save("output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }

        public void Test2()
        {
            Bitmap img = (Bitmap)pictureBox1.Image;
            using (Graphics g = Graphics.FromImage(img))
            {
                //g.Clear(Color.White);

                // 创建文本绘制器
                var drawer = new MultiTextDrawer();
                var textItems1 = new List<TextPosition>();
                for (int i = 0; i < rectangles.Count; i++)
                {
                    TextPosition textPosition= new TextPosition((i + 1).ToString(), new PointF(rectangles[i].X*2, rectangles[i].Y*2), new Font("微软雅黑", 24), Color.Red);
                    textItems1.Add(textPosition);
                }
                Console.WriteLine("textItems1.Count: "+textItems1.Count);

                // 执行绘制
                Bitmap result = drawer.DrawTexts(img, textItems1);

                //using (Graphics g1 = Graphics.FromImage(result))
                //{
                //    g1.DrawRectangle(new Pen(Color.Red, 2),new Rectangle(rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2));
                //    pictureBox1.Image = result;
                //}

                pictureBox1.Image = result;

                result.Save("output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }

        public void Test2(Bitmap img)
        {
           
            using (Graphics g = Graphics.FromImage(img))
            {
                //g.Clear(Color.White);

                // 创建文本绘制器
                var drawer = new MultiTextDrawer();
                var textItems1 = new List<TextPosition>();
                for (int i = 0; i < rectangles.Count; i++)
                {
                    TextPosition textPosition = new TextPosition((i + 1).ToString(), new PointF(rectangles[i].X * 2, rectangles[i].Y * 2), new Font("微软雅黑", 24), Color.Red);
                    textItems1.Add(textPosition);
                }
                Console.WriteLine("textItems1.Count: " + textItems1.Count);

                // 执行绘制
                Bitmap result = drawer.DrawTexts(img, textItems1);

                pictureBox1.Image = result;
                result.Save("output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            finalPointsList.Clear();
            mainInfos.Clear();
            for (int i = 0; i < rectangles.Count; i++)
            {
                Compare(rectangles[i], infosList[i],insideList[i],finalPointlists[i]);
            }
            Console.WriteLine(finalPointsList.Count);
            Console.WriteLine(mainInfos.Count);
            Image bitmap = AlgorithmModule_GPU.RectPoints1(saveBitmap, finalPointsList, mainInfos);
            //pictureBox1.Image = bitmap;
            Test2((Bitmap)bitmap);
            Console.WriteLine("infosList.Count:" + infosList.Count);
            //Test22(RectanglesSwitch_2Times(rectangles));
            //pictureBox1.Image = AlgorithmModule_GPU.RectPoints(saveBitmap, RectanglesSwitch_2Times(rectangles));
            for (int i = 0; i < infosList.Count; i++)
            {
                Console.WriteLine("infosList[i].Count:" + infosList[i].Count);

            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            List<LocalTemplateSingleInfo> localTemplateSingleInfos = new List<LocalTemplateSingleInfo>();
            for (int i = 0; i < infosList.Count; i++)
            {
                Console.WriteLine("infosList[i].Count:" + infosList[i].Count);
                if (infosList[i].Count > 0)
                {
                    LocalTemplateSingleInfo localTemplateSingleInfo = new LocalTemplateSingleInfo();
                    localTemplateSingleInfo.InfoList = infosList[i];
                    localTemplateSingleInfo.rect_X = rectangles[i].X.ToString();
                    localTemplateSingleInfo.rect_Y = rectangles[i].Y.ToString();
                    localTemplateSingleInfo.rect_Width = rectangles[i].Width.ToString();
                    localTemplateSingleInfo.rect_Height = rectangles[i].Height.ToString();
                    localTemplateSingleInfos.Add(localTemplateSingleInfo);
                }
            }
            Console.WriteLine("localTemplateSingleInfos.Count:" + localTemplateSingleInfos.Count);

            LocalTemplateSingleInfos_Config.LocalTemplateInfoSave(localTemplateSingleInfos);
        }

        List<Rectangle> RectanglesSwitch_2Times(List<Rectangle> rectangles)
        {
            List<Rectangle> finalRectangles = new List<Rectangle>();
            for (int i = 0; i < rectangles.Count; i++)
            {
                Rectangle rectangle = new Rectangle(rectangles[i].X * 2, rectangles[i].Y * 2, rectangles[i].Width * 2, rectangles[i].Height * 2);
                finalRectangles.Add(rectangle);
            }
            return finalRectangles;
        }

        //pictureBox1的初始位置
        private Point PicStartPos;
        //pictureBox1的初始大小
        private Size PicSize;
        //鼠标滚轮缩放图片的增量值
        private int ZoomStep = 20;
        private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
            if (pictureBox1.Image == null) return;
            Console.WriteLine("ZoomStep--------------"+ ZoomStep);
            PictureBox pbox = pictureBox1;
            int x = e.Location.X;
            int y = e.Location.Y;
            int ow = pbox.Width;
            int oh = pbox.Height;
            int VX, VY;  //因缩放产生的位移矢量

            int ow1 = rect.Width;
            int oh1 = rect.Height;
            int VX1, VY1;  //因缩放产生的位移矢量
            if(e.Delta > 0)
            {
                if (pbox.Width >= 1624)
                    return;

                pbox.Width = 2 * pbox.Width;
                pbox.Height = 2 * pbox.Height;
                PropertyInfo pInfo = pbox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pbox, null);
                //第3步
                pbox.Width = rect.Width;
                pbox.Height = rect.Height;

                //this.rect.Width = pbox.Width/2;
                //this.rect.Height = pbox.Height/2;
            }
            if (e.Delta < 0)
            {
                //防止一直缩成负值
                if (pbox.Width <= 406)
                    return;

                pbox.Width = pbox.Width / 2;
                pbox.Height = pbox.Height / 2;
                PropertyInfo pInfo = pbox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                 BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pbox, null);
                pbox.Width = rect.Width;
                pbox.Height = rect.Height;
            }
            if (e.Delta > 0) //放大
            {
                ////第1步
                //pbox.Width += ZoomStep;
                //pbox.Height += ZoomStep;
                ////第2步
                //PropertyInfo pInfo = pbox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
                //Rectangle rect = (Rectangle)pInfo.GetValue(pbox, null);
                ////第3步
                //pbox.Width = rect.Width;
                //pbox.Height = rect.Height;

                //this.rect.Width -= ZoomStep;
                //this.rect.Height -= ZoomStep;



                //Console.WriteLine(string.Format("宽：{0}，高：{1}",pbox.Width,pbox.Height));
            }
            if (e.Delta < 0) //缩小
            {
                ////防止一直缩成负值
                //if (pbox.Width < 300)
                //    return;

                //pbox.Width -= ZoomStep;
                //pbox.Height -= ZoomStep;
                //PropertyInfo pInfo = pbox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                // BindingFlags.NonPublic);
                //Rectangle rect = (Rectangle)pInfo.GetValue(pbox, null);
                //pbox.Width = rect.Width;
                //pbox.Height = rect.Height;
            }

            //第4步，求因缩放产生的位移，进行补偿，实现锚点缩放的效果
            VX = (int)((double)x * (ow - pbox.Width) / ow);
            VY = (int)((double)y * (oh - pbox.Height) / oh);
            pbox.Location = new Point(pbox.Location.X + VX, pbox.Location.Y + VY);

            //VX1 = (int)((double)x * (ow1 - rect.Width) / ow1);
            //VY1 = (int)((double)y * (oh1 - rect.Height) / oh1);
            //rect.Location = new Point(rect.Location.X + VX1, rect.Location.Y + VY1);
            //pictureBox1.Invalidate();
            //Bitmap img = (Bitmap)pictureBox1.Image;
            //using (Graphics g = Graphics.FromImage(originBitmap))
            //{
            //    g.DrawRectangle(new Pen(Color.Red, 2), new Rectangle(rect.X, rect.Y, rect.Width, rect.Height));
            //}

            Console.WriteLine("pbox.Width:==="+pbox.Width);
        }

        public static Image RectPoints(Bitmap bitmap, Rectangle rectangle)
        {
            Bitmap convertedImage = new Bitmap(
            bitmap.Width,
            bitmap.Height,
            PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(convertedImage))
            {
                g.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
            }

            Graphics graphics1 = Graphics.FromImage(convertedImage);

            Pen pen = new Pen(Color.Red, 3);

            graphics1.DrawRectangle(pen, rectangle);

            graphics1.Dispose();
            return convertedImage;
        }
    }
}
